<template>
  <div class="main_box" v-loading="pageLoading">
    <!--<el-row>
     <el-col :span="12">
      <div class="opration_wrap" v-has="permissionAdd">
        <el-button type="success" icon="fa fa-plus" @click="handleClickAdd()">新增</el-button>
        <el-button type="success" icon="el-icon-refresh-right" @click="reload">刷新</el-button> -->
    <!--<span class="line">|</span>-->
    <!--<el-button type="primary" icon="fa fa-mail-forward">导出</el-button>
      </div>
    </el-col>
  </el-row>-->
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="hospitalName">
              <el-input v-model="searchForm.hospitalName" clearable placeholder="医院名称"></el-input>
            </el-form-item>
            <el-form-item prop="hospitalCode">
              <el-input v-model="searchForm.hospitalCode" clearable placeholder="医院编号"></el-input>
            </el-form-item>
            <el-form-item prop="areaIds">
              <Region :areaValues="searchForm.areaIds" :isChangeOnSelect="true" @regionChange="handleRegionChange"></Region>
            </el-form-item>
            <el-form-item prop="hospitalType">
              <el-select v-model="searchForm.hospitalType" :clearable="true" placeholder="请选择医院类型">
                <el-option v-for="item in reviewStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="state">
              <el-select v-model="searchForm.state" :clearable="true" placeholder="请选择医院状态">
                <el-option v-for="item in agenciesStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button type="info" plain icon="el-icon-folder" v-has="permissionExport" @click="handleClickExport()" size="mini"> 导出</el-button>
<!--            <el-button type="success" plain icon="fa fa-plus" v-has="permissionBatchNuclePrice" @click="handleClickBatchNuclePrice()" size="mini"> 批量绑定采样价格</el-button>-->
            <el-button type="success" plain icon="el-icon-suitcase" v-has="permissionBatchSetBusinessMan" @click="handleClickBatchSetBusinessMan()" size="mini"
              >批量设置业务员</el-button
            >
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <el-table :data="tableList" @selection-change="changeSelect" :fit="true">
        <!--<el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="hospitalImageUrl" label="医院头像" width="100">
          <template slot-scope="scope">
            <img :src="scope.row.hospitalImageUrl" class="photo"/>
          </template>
        </el-table-column>-->
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="hospitalCode" label="医院编号" width="120" align="center"></el-table-column>
        <el-table-column prop="hospitalName" label="医院名称" width="220"></el-table-column>
        <el-table-column prop="contactsName" label="联系人" width="100"></el-table-column>
        <el-table-column prop="contactsTitle" label="联系人职称" width="100"></el-table-column>
        <el-table-column prop="contactsTel" label="联系人手机" width="180"></el-table-column>
        <el-table-column label="所在地区" :filter-multiple="true">
          <template slot-scope="scope">
            <span>{{ scope.row.provinceName }}</span
            ><span>{{ scope.row.cityName }}</span
            ><span>{{ scope.row.areaName }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column label="医院类型" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag :type="formatInsTypes(scope.row.hospitalType)" size="mini" effect="plain">
                {{formatInsType(scope.row.hospitalType)}}
              </el-tag>
            </span>
          </template>
        </el-table-column>-->
<!--        <el-table-column prop="isHsPay" label="支付类型" width="120" :formatter="formatIsHsPay"></el-table-column>-->
        <el-table-column label="医院状态" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag :type="formatStates(scope.row.state)" size="mini" effect="dark">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="200"></el-table-column>
        <el-table-column label="操 作" width="150" align="left">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{ scope.row.state == 0 ? '启用' : '禁用' }}</el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" v-if="scope.row.state == 0" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <!--设置业务员组件 -->
    <BatchSetBusinessMan ref="batchSetBusinessMan" :relation-type="2"></BatchSetBusinessMan>

    <el-dialog title="批量绑定采样价格模板" :visible.sync="hideDialogShow" :center="true" width="600px">
      <el-form :model="dataForm" ref="dataForm" :rules="roleRules" label-width="150px">
        <el-form-item label="采样价格模板" prop="modelId">
          <el-select v-model="dataForm.modelId" filterable clearable reserve-keyword placeholder="请选择采样价格模板">
            <el-option v-for="item in pickNuclePriceModelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item align="center">
          <el-button type="primary" plain @click.native="clickCommit">确 定</el-button>
          <el-button @click.native="clickCancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import HospitalApi from '@/api/institution/hospital';
import NuclePriceApi from '@/api/sample/nuclePrice';
import Region from '@/components/Region';
import BatchSetBusinessMan from '@/components/BatchSetBusinessMan';

export default {
  name: 'HospitalManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      tableList: [],

      excelData: {},
      allList: [],
      selectIds: [],
      pickNuclePriceModelList: [],
      pageLoading: false,
      hideDialogShow: false,
      dataForm: {
        modelId: '',
        idList: [],
        type: 1,
      },
      roleRules: {
        mainFlag: [{ required: true, message: '请选择采样价格模板', trigger: 'change' }],
      },
      page: {
        pageNo: 1,
        pageSize: 20,
        pageTotal: 0,
      },
      searchForm: {
        hospitalName: '',
        hospitalCode: '',
        hospitalType: '',
        provinceId: '',
        cityId: '',
        areaId: '',
        areaIds: [],
        state: '',
      },
      reviewStatue: [
        { label: '合作医院', value: 1 },
        { label: '其他医院', value: 2 },
      ],
      agenciesStatue: [
        { label: '禁用', value: '0' },
        { label: '启用', value: '1' },
        /* { label: "待审核", value:"2"}*/
      ],
      permissionAdd: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_DELETE',
      permissionBatchNuclePrice: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_BATCH_NUCLE_PRICE',
      permissionBatchSetBusinessMan: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_BATCH_SET_BUSINESS_MAN',
      permissionExport: 'SYSTEM_MANAGER_INSTITU_HOSPITAL_LIST_EXPORT',
    };
  },
  components: {
    Region,
    BatchSetBusinessMan,
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.init();
    if (this.$route.params.hospitalId) {
      let hospitalItem = this.tableList.filter((item) => {
        return item.hospitalId == this.$route.params.hospitalId;
      });
      let index = this.tableList.indexOf(hospitalItem[0]);
      for (let item in this.tableList[index]) {
        if (this.$route.params[item]) {
          this.tableList[index][item] = this.$route.params[item];
        }
      }
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      this.listTable();
      //this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    formatInsType(cellValue) {
      if (cellValue === 1) {
        return '合作医院';
      } else if (cellValue === 2) {
        return '其他医院';
      }
    },
    formatInsTypes(cellValue) {
      if (cellValue === 1) {
        return '';
      } else if (cellValue === 2) {
        return 'warning';
      }
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      } else if (cellValue === 2) {
        return '待审核';
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return 'danger';
      } else if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      } else if (cellValue === 2) {
        return '';
      }
    },
    formatIsHsPay(row, column, cellValue) {
      if (cellValue === 0) {
        return '月结';
      } else if (cellValue === 1) {
        return '预约支付';
      } else if (cellValue === 2) {
        return '采样支付';
      }
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectIds.push(val[i].hospitalId);
      }
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    handleClickAdd() {
      this.$router.push('/institu/hospitalAdd');
    },
    handleClickEditor(row) {
      this.$router.push({
        path: '/institu/hospitalEdit',
        query: { id: row.hospitalId },
      });
    },
    /*handleClickAdManager(row){
      this.$router.push({path: "/user/HospitalAdManager", query: {id: row.hospitalId}})
    },
    handleClickQualificationsEditor(row){
      this.$router.push({path: "/user/HospitalQualificationEdit", query: {id: row.hospitalId}})
    },
    handleClickEnvironmentEditor(row){
      this.$router.push({path: "/user/HospitalEnvironmentEdit", query: {id: row.hospitalId}})
    },*/
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let deleteFormData = {
          hospitalId: row.hospitalId,
          state: -1,
        };
        HospitalApi.deleteHospital(deleteFormData).then((res) => {
          this.listTable();
          this.$Utils.notifySuccess();
        });
      });
    },
    handleClickDetail(row) {
      this.$router.push({
        path: '/institu/hospitalDetail',
        query: { id: row.hospitalId },
      });
    },
    handleIsDisable(row) {
      let currentState = row.state === 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        let disableFormData = {
          hospitalId: row.hospitalId,
          state: currentState,
        };
        HospitalApi.deleteHospital(disableFormData).then((res) => {
          row.state = currentState;
          this.$Utils.notifySuccess();
        });
      });
    },
    handleRegionChange(val) {
      this.searchForm.provinceId = val.provinceId;
      this.searchForm.cityId = val.cityId;
      this.searchForm.areaId = val.areaId;
      this.searchForm.areaIds = [val.provinceId, val.cityId, val.areaId];
    },
    /*handleAudit(row){
      this.$router.push({path: "/user/hospitalAudit", query: {id: row.hospitalId}})
    },*/
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.searchForm.provinceId = '';
      this.searchForm.cityId = '';
      this.searchForm.areaId = '';
      this.onSearch();
    },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        hospitalName: this.searchForm.hospitalName,
        hospitalType: this.searchForm.hospitalType,
        provinceId: this.searchForm.provinceId,
        cityId: this.searchForm.cityId,
        areaId: this.searchForm.areaId,
        state: this.searchForm.state,
      };
      HospitalApi.getHospitalList(data).then((res) => {
        this.tableList = res.data.list;
        this.page.pageTotal = res.data.total;
      });
    },
    clickCommit() {
      this.$confirm(message.MSG_CONFIRM_BATCH_SAMPLE_PRICE, message.TITLE_PROMPT, {}).then(() => {
        this.dataForm.idList = this.selectIds;
        NuclePriceApi.bindModel(this.dataForm).then((res) => {
          this.hideDialogShow = false;
          this.$Utils.notifySuccess();
          this.listTable();
        });
      });
    },
    clickCancel() {
      this.hideDialogShow = false;
    },
    handleClickBatchNuclePrice() {
      this.hideDialogShow = true;
      this.dataForm.modelId = '';
      if (!this.pickNuclePriceModelList || this.pickNuclePriceModelList.length === 0) {
        this.getNuclePriceModelList();
      }
    },
    handleClickBatchSetBusinessMan() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        _this.$refs.batchSetBusinessMan.handleCreate(this.selectIds);
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请至少选择一条记录！',
        });
      }
    },
    getNuclePriceModelList() {
      let _this = this;
      NuclePriceApi.listModelName({}).then((res) => {
        setTimeout(() => {
          _this.pickNuclePriceModelList = res.data.map((item) => {
            return {
              value: item.id,
              label: item.name,
            };
          });
        }, 200);
      });
    },
    async handleClickExport() {
      await this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      });
      const data = { ...this.searchForm };
      delete data.areaIds;
      this.pageLoading = true;
      const res = await HospitalApi.getAllHospital(data);
      this.excelData = res.data;
      this.pageLoading = false;
      this.export2Excel();
    },
    export2Excel() {
      let that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel'); //这里必须使用绝对路径
        const tHeader = ['医院名称', '省', '市', '区', '详细地址', '联系人', '联系电话', '创建人', '创建时间']; // 导出的表头名
        const filterVal = ['hospitalName', 'provinceName', 'cityName', 'areaName', 'hospitalAddress', 'contactsName', 'contactsTel', 'createUserName', 'createDate']; // 导出的表头字段名
        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        let currentTime = this.$Utils.formatDate(new Date(), 'yyyy-MM-dd');
        export_json_to_excel(tHeader, data, `康来医院数据_${currentTime}`); // 导出的表格名称，根据需要自己命名
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
